package com.example.administrator.bluetooth_data_transmission;

import android.bluetooth.BluetoothGattCharacteristic;
import android.os.Bundle;
import android.os.Debug;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.bluetooth_data_transmission.bean.ReadDataBean;
import com.example.administrator.bluetooth_data_transmission.command.Command;
import com.example.administrator.bluetooth_data_transmission.util.DigitalTrans;
import com.example.administrator.bluetooth_data_transmission.util.SaveToExcelUtil;
import com.example.administrator.bluetooth_data_transmission.util.ToastUtil;
import com.orhanobut.hawk.Hawk;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.logging.Logger;

import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.BleDevice;
import cn.com.heaton.blelibrary.ble.callback.BleNotiftCallback;
import cn.com.heaton.blelibrary.ble.callback.BleWriteCallback;


/**
 *
 *  FA A6 00 00 12 11 0A 05 0F 09
 *
 * */

public class ReadDataActivity extends BaseActivity implements View.OnClickListener {

    private String TAG = BlueToothListActivity.class.getSimpleName();

    private Button btn_data_read, btn_real_time, btn_pause,btn_save;
    private TextView tv_time,tv_dev,tv_azim;
    private Ble<BleDevice> mBle;
    private byte[] b;
    private List<ReadDataBean> data ;
    private String BleStr = "";
    private SaveToExcelUtil saveToExcelUtil;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_read_data);
        mBle = Ble.getInstance();
        if (mBle.getConnetedDevices().size() > 0) {
            mBle.startNotify(mBle.getConnetedDevices().get(0), bleNotiftCallback);
        }
        initView();
        initListener();
    }

    private void initListener() {
        btn_data_read.setOnClickListener(this);
        btn_real_time.setOnClickListener(this);
        btn_pause.setOnClickListener(this);
        btn_save.setOnClickListener(this);
    }

    protected void initView() {
        if(!getIntent().getStringExtra("FILENAME").isEmpty()){
            String etName = getIntent().getStringExtra("FILENAME");
            BleStr = Environment.getExternalStorageDirectory().toString()+ File.separator+etName+ File.separator+"data.xls";
            saveToExcelUtil = new SaveToExcelUtil(this, BleStr);
        }
        btn_data_read = findViewById(R.id.btn_data_read);
        btn_real_time = findViewById(R.id.btn_real_time);
        btn_pause = findViewById(R.id.btn_pause);
        btn_save = findViewById(R.id.btn_save);
        tv_time = findViewById(R.id.tv_time);
        tv_dev = findViewById(R.id.tv_dev);
        tv_azim = findViewById(R.id.tv_azim);
    }

    @Override
    public void onClick(View v) {
        List<BleDevice> list = Ble.getInstance().getConnetedDevices();
        switch (v.getId()) {
            case R.id.btn_data_read:
                data = new ArrayList<>();
                synchronized (mBle.getLocker()) {
                    for (BleDevice device : list) {
                        sendData(device, (byte) 0x11);
                    }
                }
                break;
            case R.id.btn_real_time:
                data = null;
                synchronized (mBle.getLocker()) {
                    for (BleDevice device : list) {
                        sendData(device, (byte) 0x16);
                    }
                }
                break;
            case R.id.btn_pause:
                synchronized (mBle.getLocker()) {
                    for (BleDevice device : list) {
                        sendData(device, (byte) 0x17);
                    }
                }
                break;
            case R.id.btn_save:

                if(data!=null){
                    Hawk.put("BLEDATA",data);
                    for(int i = 0;i<data.size();i++){
                        saveToExcelUtil.writeToExcel1("","","","",data.get(i).time,data.get(i).DEV,data.get(i).AZIM);
                    }

                    Log.e("YYJ",data.size()+"");
                }else {
                    ToastUtil.showToast("请先读取数据");
                }

                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        mBle.cancelNotify(new BleNotiftCallback<BleDevice>() {
            @Override
            public void onChanged(BleDevice device, BluetoothGattCharacteristic characteristic) {

            }
        });
    }

    //数据包
    public byte[] changeLevelInner(byte changeData) {
        byte[] data = new byte[Command.qppDataSend.length];
        System.arraycopy(Command.qppDataSend, 0, data, 0, data.length);
        data[2] = changeData;
        return data;
    }

    /*发送数据*/
    public void sendData(BleDevice device,byte changeData) {
        boolean result = mBle.write(device, changeLevelInner(changeData),
                new BleWriteCallback<BleDevice>() {
                    @Override
                    public void onWriteSuccess(BluetoothGattCharacteristic characteristic) {
                        Toast.makeText(ReadDataActivity.this,"发送成功",Toast.LENGTH_SHORT).show();
                    }
                });
        if (!result) {
            ToastUtil.showToast("发送数据失败!");
        }
    }

    /*设置通知的回调*/
    private BleNotiftCallback<BleDevice> bleNotiftCallback = new BleNotiftCallback<BleDevice>() {
        @Override
        public void onChanged(BleDevice device, BluetoothGattCharacteristic characteristic) {
            b = characteristic.getValue();
            ReadDataBean bean = new ReadDataBean();
            if(b.length>=10&&b.length<20){
                String time = DigitalTrans.byte4ToInt(b[2],b[3],b[4],b[5]);
                String dev = DigitalTrans.byte2ToInt(b[6],b[7]);
                String azim = DigitalTrans.byte2ToInt(b[8],b[9]);
                if(data !=null){
                    bean.time = time;
                    bean.DEV = dev;
                    bean.AZIM = azim;
                    data.add(bean);
                }
                tv_time.setText(time);
                tv_dev.setText(dev);
                tv_azim.setText(azim);
            }else if(b.length == 20){
                String time = DigitalTrans.byte4ToInt(b[2],b[3],b[4],b[5]);
                String dev = DigitalTrans.byte2ToInt(b[6],b[7]);
                String azim = DigitalTrans.byte2ToInt(b[8],b[9]);
                String time1 = DigitalTrans.byte4ToInt(b[12],b[13],b[14],b[15]);
                String dev1 = DigitalTrans.byte2ToInt(b[16],b[17]);
                String azim1 = DigitalTrans.byte2ToInt(b[18],b[19]);
                if(data!=null){
                    bean.time = time;
                    bean.DEV = dev;
                    bean.AZIM = azim;
                    data.add(bean);
                    bean.time = time1;
                    bean.DEV = dev1;
                    bean.AZIM = azim1;
                    data.add(bean);
                }
                tv_time.setText(time);
                tv_dev.setText(dev);
                tv_azim.setText(azim);
            }
//            String hs = "";
//            String stmp = "";
//            for (int i = 0; i < b.length; i++) {
//                stmp = Integer.toHexString(b[i] & 0xff);
//                if (stmp.length() == 1) {
//                    hs = hs + "0" + stmp + " ";
//                } else {
//                    hs = hs + stmp + " ";
//                }
//            }
//            Log.e(TAG, "onChanged: " + hs.toUpperCase() + " ");
//            UUID uuid = characteristic.getUuid();
//            Log.e(TAG, "onChanged==uuid:" + uuid.toString());
//            Log.e(TAG, "onChanged==address:" + device.getBleAddress());
//            Log.e(TAG, "onChanged==data:" + Arrays.toString(characteristic.getValue()));
        }
    };
}
